package com.kpmg.questionnaire.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.kpmg.questionnaire.model.AnswerEntity;
import com.kpmg.questionnaire.model.EmailEntity;
import com.kpmg.questionnaire.model.QuestionEntity;
import com.kpmg.questionnaire.model.UserEntity;
import com.kpmg.questionnaire.repository.AnswerRepository;
import com.kpmg.questionnaire.repository.EmailRepository;
import com.kpmg.questionnaire.repository.QuestionRepository;
import com.kpmg.questionnaire.service.IEmailService;
import com.kpmg.questionnaire.utils.FreemarkerUtils;
import com.kpmg.questionnaire.utils.WebConstants;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * Created by xionghao on 2016/11/9.
 */
@Controller
public class AnswerController {
	// 自动装配数据库接口，不需要再写原始的Connection来操作数据库

	@Autowired
	private AnswerRepository answerRepository;

	@Autowired
	private IEmailService emailService;

	@Autowired
	private Executor mailTaskExecutor;

	@Autowired
	private ServletContext servletContext;

//	@Autowired
//	private EmailRepository emailRepository;

	// UserRepository userRepository;

	// 答案查看
	@RequestMapping(value = "/answer", method = RequestMethod.GET)
	public String showAnswer(ModelMap modelMap) {
		// List<QuestionEntity> questionList = questionRepository.findAll();
		List<AnswerEntity> list = answerRepository.findAll();
		modelMap.addAttribute("list", list);
		return "answer/list";
	}

	// 答案添加
	@RequestMapping(value = "/answer/addItem", method = RequestMethod.GET)
	public String addItem() {
		return "answer/addItem";
	}

	@Autowired
	private QuestionRepository questionRepository;

	private Date createTime;

	// 添加处理
	@ResponseBody
    @RequestMapping(value = "/answer/addItemPost", method = RequestMethod.POST)
    public String addItemPost(@ModelAttribute("answer") AnswerEntity answerEntity, HttpServletRequest request) {
        // 向数据库添加一个表单，并将内存中缓存区的数据刷新，立即写入数据库，之后才可以进行访问读取
        //添加当前日期
        createTime =  new Date(System.currentTimeMillis());
        answerEntity.setCreateDate(createTime);
        answerRepository.saveAndFlush(answerEntity);
        List<QuestionEntity> questions = questionRepository.findAll();   //问题

        String realPath = request.getSession().getServletContext().getRealPath("/pdf");
        UserEntity userEntity = (UserEntity)request.getSession().getAttribute(WebConstants.SESSION_USER_KEY);
        
        mailTaskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				emailService.sendEvaluationResultsEmail(answerEntity, questions, realPath, userEntity);
			}
		});
        
        // 返回重定向页面
        return "true";
    }

	// 添加处理
	@ResponseBody
	@RequestMapping(value = "/answer/sendEmail", method = RequestMethod.POST)
	public String sendEmail(@ModelAttribute("answer") AnswerEntity answerEntity, HttpServletRequest request) {
		// 向数据库添加一个表单，并将内存中缓存区的数据刷新，立即写入数据库，之后才可以进行访问读取
		// 添加当前日期
		createTime = new Date(System.currentTimeMillis());
		answerEntity.setCreateDate(createTime);
		answerRepository.saveAndFlush(answerEntity);
		List<QuestionEntity> questions = questionRepository.findAll(); // 问题
		UserEntity userEntity = (UserEntity) request.getSession().getAttribute(WebConstants.SESSION_USER_KEY);
		String realPath = request.getSession().getServletContext().getRealPath("/pdf");

		mailTaskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				emailService.sendEvaluationResultsEmail(answerEntity, questions, realPath, userEntity);
			}
		});

		// 返回重定向页面
		return "true";
	}

	// 返回结果
	@RequestMapping(value = "/results", method = RequestMethod.GET)
	public String showResults() {
		// List<QuestionEntity> questionList = questionRepository.findAll();
		// List<AnswerEntity> list = answerRepository.findAll();
		// modelMap.addAttribute("list", list);
		// emailService.emailManage();

		return "answer/results";
	}

}
